package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

type YearMonsterCC struct {
}
type HeartBeat struct {
	Version        string `json:"version"`
	Chaincode_name string `json:"chaincode_name"`
	Peer_name      string `json:"peer_name"`
	Send_date      string `json:"send_date"`
}

func (t *YearMonsterCC) Init(stub shim.ChaincodeStubInterface) pb.Response {
	// httpPost("3")
	return shim.Success(nil)
}

var usage = `
	add key value      数据上链，返回状态码200或者错误信息
	query key          数据查询，返回状态码200或者错误信息
	addCert key cert   新增，接收cert的base64格式信息，返回状态码200或者错误信息
	queryCer key       查询，返回数据详情
`

func (t *YearMonsterCC) Invoke(stub shim.ChaincodeStubInterface) (res pb.Response) {
	defer func() {
		if err := recover(); err != nil {
			res = shim.Error(fmt.Sprintf("%v", err))
		}
	}()

	args := stub.GetArgs()

	if len(args) != 2 && len(args) != 3 {
		panic(usage)
	}

	fcn := string(args[0])

	switch fcn {
	case "add":
		return t.add(stub, args[1:])
	case "query":
		return t.query(stub, args[1:])
	case "addCert":
		return t.addCert(stub, args[1:])
	case "queryCert":
		return t.queryCert(stub, args[1:])
	default:
		return shim.Error("Unknown Function")
	}

	return shim.Success(nil)
}
func (t *YearMonsterCC) add(stub shim.ChaincodeStubInterface, args [][]byte) (res pb.Response) {
	key := string(args[0])
	//value := string(args[1])

	err := stub.PutState(key, args[1])
	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success(nil)
}

func (t *YearMonsterCC) query(stub shim.ChaincodeStubInterface, args [][]byte) (res pb.Response) {
	key := string(args[0])
	//value := string(args[1])

	value, err := stub.GetState(key)
	if err != nil {
		return shim.Error(err.Error())
	}
	if value != nil {
		return shim.Success(value)
	}
	return shim.Error("Cannot find this key[" + key + "].")

}

func (t *YearMonsterCC) addCert(stub shim.ChaincodeStubInterface, args [][]byte) (res pb.Response) {
	fmt.Printf("addCert: %s\n", args)

	err := stub.PutState(string(args[0]), args[1])
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success(nil)
}

func (t *YearMonsterCC) queryCert(stub shim.ChaincodeStubInterface, args [][]byte) (res pb.Response) {
	fmt.Printf("queryCert: %s\n", args)
	value, err := stub.GetState(string(args[0]))
	if err != nil {
		return shim.Error("Failed to get state")
	}
	if value == nil {
		return shim.Error("Entity not found")
	}
	return shim.Success(value)
}

func main() {
	// httpPost("main")
	err := shim.Start(new(YearMonsterCC))
	if err != nil {
		fmt.Printf("Error starting YearMonsterCC chaincode: %s", err)
	}
}

const METHOD = "POST"
const CONTENT_TYPE = "application/json"
const APP_KEY = "test_report-portal"

func httpPost(ty string) {
	//定义相关参数
	// url := "http://192.168.123.29/test.php"
	url := "http://192.168.31.140/api/baas/chaincode/v3/chainCodeStatusRefresh"

	heartBeat := HeartBeat{
		Chaincode_name: "year",
		Peer_name:      "peer0.org1.example.com",
		Send_date:      "1698247970",
		Version:        "v1.1"}
	fmt.Println(heartBeat)

	//JSON序列化
	configData, _ := json.Marshal(heartBeat)
	param := bytes.NewBuffer([]byte(configData))

	//构建http请求
	client := &http.Client{}
	req, err := http.NewRequest(METHOD, url, param)

	if err != nil {
		fmt.Println(err)
		return
	}
	//header
	req.Header.Add("Content-Type", CONTENT_TYPE)
	req.Header.Add("appKey", APP_KEY)

	//发送请求
	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	//返回结果
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(body))

}

func GetHealth(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "ok")
}
